//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Common
//  File name:	CamlQueryBuilderConditionItem.cs
//  Developer:	Solomatov Igor
//  Created:	15.04.2012
// 
//  -------------------- iSharePoint -------------------- //

using System.ComponentModel;

namespace Smart.Common.Entities
{
	/// <summary>
	/// QueryBuilder Query Condition Item
	/// </summary>
	[Localizable(false)]
	public class CamlQueryBuilderConditionItem<TExecutorType> : CamlQueryBuilderItem<TExecutorType>
		where TExecutorType : class
	{
		/// <summary>
		/// Field
		/// </summary>
		public string Field { get; set; }

		/// <summary>
		/// Value type
		/// </summary>
		public string ValueType { get; set; }

		/// <summary>
		/// Value
		/// </summary>
		public string Value { get; set; }

		/// <summary>
		/// QueryBuilder Query Condition Item
		/// </summary>
		/// <param name="field">Field name</param>
		/// <param name="op">Operator</param>
		/// <param name="valueType">Value type</param>
		/// <param name="value">Value</param>
		public CamlQueryBuilderConditionItem(string field, string op, string valueType, string value)
			: base(op)
		{
			this.Field = field;
			this.ValueType = valueType;
			this.Value = value;
		}

		/// <summary>
		/// Return Cache code
		/// </summary>
		public override int GetCacheCode()
		{
			return
				(Field == null ? 0 : Field.GetHashCode()) ^
				(Op == null ? 0 : Op.GetHashCode()) ^
				(ValueType == null ? 0 : ValueType.GetHashCode()) ^
				(Value == null ? 0 : Value.GetHashCode());
		}

		/// <summary>
		/// Format QueryBuilder statement
		/// </summary>
		public override string FormatQuery()
		{
			string fieldName = (Query == null ? Field : Query.Meta.FieldName(Field));

			if (fieldName.EqIC(SN.IDField) && ValueType.EqIC("Integer"))
				ValueType = "Counter";

			return
				string.Format("<{1}><FieldRef Name=\"{0}\"/><Value Type=\"{2}\">{3}</Value></{1}>", fieldName, Op, ValueType, Value.EncodeXml());
		}
	}
}